package apis

import (
	"encoding/json"
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	jwt2 "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
	"tuowei.com/app/api/models"
	"tuowei.com/pkg/xlog"
)

type Base struct {
	StudentID int
}

type InviteClaims struct {
	Id int
	jwt.StandardClaims
}

type StudentClaims struct {
	Student *models.SysStudent
	jwt.StandardClaims
}

func (b Base) GetUser(e *api.Api) (error, int) {
	value, _ := e.Context.Get(jwt2.JwtPayloadKey)
	bytes, _ := json.Marshal(value)
	obj := new(StudentClaims)
	err := json.Unmarshal(bytes, &obj)
	if err != nil || obj == nil {
		xlog.Error(err)
		return errors.New("token 过期"), 0
	}

	b.StudentID = obj.Student.Id

	return nil, obj.Student.Id
}

func (b Base) GetUserObject(e *api.Api) (*models.SysStudent, error) {
	value, _ := e.Context.Get(jwt2.JwtPayloadKey)
	bytes, _ := json.Marshal(value)
	obj := new(StudentClaims)
	err := json.Unmarshal(bytes, &obj)
	if err != nil {
		return nil, err
	}
	return obj.Student, nil
}
